import {Component, OnInit, ViewChild} from '@angular/core'
import { ApiService } from 'projects/product/src/app/services/api.service'
import { ModalRef } from '@app/shared/utils'
import {CursorService} from "@core/http/cursor.service";
import {DataTableComponent} from "@shared/components/data-table/data-table.component";

@Component({
  selector: 'app-select-pruduct',
  templateUrl: './select-pruduct.component.html',
  styleUrls: ['./select-pruduct.component.scss'],
  providers: [ModalRef]
})
export class SelectPruductComponent implements OnInit {
  public catalogList: any[] = []
  public productList: any[] = []

  @ViewChild(DataTableComponent,{static:true})
  dataTable:DataTableComponent

  constructor(private apiService: ApiService,
              public modalRef: ModalRef,
              public cursorService: CursorService) {}

  ngOnInit() {
    this.getProductCatalogList()
  }
  add(){
    let data =this.dataTable.getSelection();

    for(let item of data) {
      item['count']=1
    }
    // console.log('Data:'+JSON.stringify(data))
    this.modalRef.close(data);
  }
  /**
   * 选择标签类型改变
   * @param param0
   */
  public onCatalogChange($event) {
    console.log(JSON.stringify($event))
    if ($event['action'] === 'click') {
      this.getProductList($event['treeNodeID'])
    }
  }

  /**
   * 获取标签列表
   * @param parent
   */
  private getProductList(id) {
    this.productList =[];
    this.cursorService.limit= 10;
    this.cursorService.statement="select * where catalogno="+"'"+id+"'",
      this.apiService.getProductList(this.cursorService).subscribe(data => {
        // console.log('产品数据为：'+JSON.stringify(data))
        this.productList = data
      })

  }
  private getProductCatalogList() {
    this.cursorService.limit =1000;
    this.cursorService.statement='select *';
    this.apiService.getCatalogList(this.cursorService).subscribe(data => {
      this.catalogList = JSON.parse(JSON.stringify(data).replace(/catalogName/g, 'label'));
      this.catalogList = JSON.parse(JSON.stringify(this.catalogList).replace(/subcatalogs/g, 'children'));
      this.catalogList = JSON.parse(JSON.stringify(this.catalogList).replace(/catalogNo/g, 'id'));
      console.log(' this.catalogList: '+JSON.stringify(this.catalogList))
      // 添加label字段
      // list.forEach((x: any) => {
      //   x.label = x.catalogName
      // })
      // 生成树形结构
      // this.catalogList = this.generateCatalogTree(list)
    })
  }

  // private generateCatalogTree(list) {
  //   const root = list.filter(x => !x.subcatalogs)
  //
  //   const depth = node => {
  //     const children = list.filter(x => x.parent === node.id)
  //
  //     if (children && children.length) {
  //       node.children = children
  //       node.children.forEach(depth)
  //     } else {
  //       node.leaf = true
  //     }
  //     return node
  //   }
  //
  //   return root.map(depth)
  // }
}
